<template>
  <div class="contentShadow">
    <el-container>
      <el-header>
        <h1>修改密码</h1>
      </el-header>
      <el-main>
        <div>
          <el-form ref="form" :model="password" :rules="rules" label-width="100px">
            <el-form-item label="旧密码" prop="old">
              <el-input v-model="password.old" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new">
              <el-input v-model="password.new" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new2">
              <el-input v-model="password.new2" type="password">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import {changePassword} from '@/api/changePassword.js'
import {removeToken} from "@/utils/auth";

export default {
  name: "ChangePassword",
  data() {
    return {
      password: {
        old: "",
        new: "",
        new2: "",
      },
      rules: {
        old: [{required: true, message: "请输入旧密码", trigger: "blur"},],
        new: [{required: true, message: "请输入新密码", trigger: "blur"}],
        new2: [{required: true, message: "请再次输入新密码", trigger: "blur"}],
      },
      loading: false
    };
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.password.new != this.password.new2) {
            this.$message.error('新密码不一致')
            return
          }
          // TODO: send user data to backend
          this.loading = true
          //console.log(this.password);
          changePassword(this.password.old, this.password.new).then(res => {
            console.log(res)
            if (res.code == 50003) {
              this.loading = false
              this.$message.error(res.msg)
            } else {
              this.loading = false
              this.$refs.form.resetFields();
              this.$message.success('修改成功')
              removeToken()
              this.$router.push({path: '/login'})
            }
          }).catch(() => {
            this.loading = false
            this.$message.error('修改失败')
          })

        } else {
          console.log("form validation failed");
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style scoped>
.change {
  margin: 20px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
